<template>
  <view class="search-box">
    <!-- 使用 uni-ui 提供的搜索组件 -->
    <uni-search-bar
      @input="input"
      :radius="100"
      cancelButton="none"
    ></uni-search-bar>
    <!-- 搜索建议列表 -->
    <view class="sugg-list" v-if="searchResults.length > 0">
      <navigator
        v-for="item in searchResults"
        class="sugg-item"
        :key="item.goods_id"
        :url="'/subpkg/goods_detail/index?goods_id=' + item.goods_id"
      >
        <text class="goods-name">{{ item.goods_name }}</text>
      </navigator>
    </view>
    <!-- 搜索历史 -->
    <view v-else class="history-box">
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="17" @click="clearHistory"></uni-icons>
      </view>
      <!-- 列表区域 -->
      <view class="history-list">
        <uni-tag
          v-for="item in historys"
          :key="item"
          :text="item"
          @click="goToGoodsList(item)"
        ></uni-tag>
      </view>
    </view>
  </view>
</template>

<script>
import { request } from '@/utils/request'
export default {
  data () {
    return {
      timer: null, // 防抖用的定时器
      keyword: '', // 搜索关键字
      // 搜索结果列表
      searchResults: [],
      // 搜索关键词的历史记录
      historyList: []
    }
  },
  onLoad () {
    this.historyList = uni.getStorageSync('history') || []
  },
  computed: {
    historys () {
      return [...this.historyList].reverse()
    }
  },
  methods: {
    input (e) {
      // 清除 timer 对应的延时器
      clearTimeout(this.timer)

      // 重新启动一个延时器，并把 timerId 赋值给 this.timer
      this.timer = setTimeout(() => {
        // 如果 500 毫秒内，没有触发新的输入事件，则为搜索关键词赋值
        this.keyword = e

        this.search()
      }, 500)
    },
    async search () {
      if (this.keyword.trim() === '') {
        this.searchResults = []
        return
      }

      const res = await request({
        url: '/api/public/v1/goods/qsearch',
        data: {
          query: this.keyword
        }
      })

      if (res.meta.status === 200) {
        this.searchResults = res.message

        // 保存搜索结果
        this.saveSearchHistory(this.keyword)
      }
    },
    saveSearchHistory (keyword) {
      // 去重保存
      const historyList = new Set(this.historyList)
      // 先把之前存在的删除掉
      historyList.delete(keyword)
      // 再保存进去
      historyList.add(keyword)
      // 把它赋值给historyList
      this.historyList = Array.from(historyList)
      // 保存到本地
      uni.setStorageSync('history', this.historyList)
    },
    clearHistory () {
      this.historyList = []
      uni.setStorageSync('history', [])
    },
    // 跳转到商品列表
    goToGoodsList (item) {
      uni.navigateTo({
        url: '/subpkg/goods_list/index?query=' + item
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.search-box {
  position: sticky;
  top: 0;
  z-index: 999;
  ::v-deep .uni-searchbar {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: row;
    position: relative;
    padding: 16rpx;
    /* 将默认的 #FFFFFF 改为 #C00000 */
    background-color: #c00000;
  }

  .history-box {
    padding: 0 5px;

    .history-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 40px;
      font-size: 13px;
      border-bottom: 1px solid #efefef;
    }

    .history-list {
      display: flex;
      flex-wrap: wrap;

      ::v-deep .uni-tag {
        margin-top: 5px;
        margin-right: 5px;
      }
    }
  }

  .sugg-list {
    padding: 0 5px;

    .sugg-item {
      font-size: 12px;
      padding: 13px 0;
      border-bottom: 1px solid #efefef;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .goods-name {
        // 文字不允许换行（单行文本）
        white-space: nowrap;
        // 溢出部分隐藏
        overflow: hidden;
        // 文本溢出后，使用 ... 代替
        text-overflow: ellipsis;
        margin-right: 3px;
      }
    }
  }
}
</style>
